<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElIcon } from 'element-plus';
import { Upload } from '@element-plus/icons-vue';
import db from '../../utils/database.js'

// 引入electron API（通过预加载脚本暴露）
// declare const window: {
//   electronAPI: {
//     openDirectory: (path: string) => Promise<void>;
//   };
// };

// 表名列表（最多8张表）
const TABLE_NAMES = [
  'new_leader_report',
  'problem_clues_situation',
  'discipline_organization_punishment',
  'personal_matters_report_punishment',
  'party_conduct_opinion_reply',
  'other_clean_government_materials',
  'leader_personnel_infro',
  'subUnits'
];

// 系统字段（需要自动添加到所有查询中）
const SYSTEM_FIELDS = [
  'id',
  'created_at',
  'updated_at',
  'created_by',
  'updated_by'
];
const activeTab = ref('release');
const subTab = ref('release');
import TopNav from './navmenu.vue'

const releaseFilter = ref({ 
  exportId: '', // export_id
  timeRange: [] // 时间范围
});
const exportGroups = ref([]);
const receiveFilter = ref({ unit: '' });

// 获取分组数据
const getExportGroups = async () => {
  try {
    // 从export表获取分组数据
    const result = await db.query(`
      SELECT export_id as value, export_name as label 
      FROM export 
      ORDER BY export_name
    `);
    exportGroups.value = result;
  } catch (error) {
    ElMessage.error('获取分组数据失败');
    console.error(error);
  }
};

// 获取delieve_log数据并关联export表
const getDelieveLogData = async () => {
  try {
    // 首先查询delieve_log表
    const logResult = await db.query(`
      SELECT id, group_name, time_range, file_name, export_path, created_at 
      FROM delieve_log 
      ORDER BY created_at DESC
    `);
    
    if (logResult.length === 0) {
      releaseTableData.value = [];
      return;
    }
    
    // 获取所有唯一的export_id
    const exportIds = [...new Set(logResult.map(item => item.group_name))];
    
    // 查询export表获取对应的export_name
    const exportNamesQuery = exportIds.map(id => `SELECT '${id}' as export_id, export_name FROM export WHERE export_id = '${id}'`).join(' UNION ');
    const exportNamesResult = await db.query(exportNamesQuery);
    
    // 创建export_id到export_name的映射
    const exportNameMap = {};
    exportNamesResult.forEach(item => {
      exportNameMap[item.export_id] = item.export_name;
    });
    
    // 将group_name替换为对应的export_name
    const processedData = logResult.map(item => ({
      ...item,
      group_name: exportNameMap[item.group_name] || item.group_name
    }));
    
    releaseTableData.value = processedData;
  } catch (error) {
    ElMessage.error('获取日志数据失败');
    console.error(error);
  }
};

// 页面加载时获取分组数据和日志数据
onMounted(async () => {
  getExportGroups();
  getDelieveLogData();
  
  // 初始化数据接收表格数据
  await handleReceiveExecute();
});

const releaseTableData = ref([]);
const receiveTableData = ref([]);

// 发放数据分页
const releasePagination = ref({
  currentPage: 1,
  pageSize: 10
});

// 接收数据分页
const receivePagination = ref({
  currentPage: 1,
  pageSize: 10
});

// 计算发放数据分页后的结果
const paginatedReleaseData = computed(() => {
  const start = (releasePagination.value.currentPage - 1) * releasePagination.value.pageSize;
  const end = start + releasePagination.value.pageSize;
  return releaseTableData.value.slice(start, end);
});

// 计算接收数据分页后的结果
const paginatedReceiveData = computed(() => {
  const start = (receivePagination.value.currentPage - 1) * receivePagination.value.pageSize;
  const end = start + receivePagination.value.pageSize;
  return receiveTableData.value.slice(start, end);
});

const handleReleaseExecute = () => {
  // ElMessage.info('执行数据发放查询');
  // 现在直接使用delieve_log数据，不需要模拟数据
  getDelieveLogData();
  releasePagination.value.currentPage = 1;
};

const handleReceiveExecute = async () => {
  try {
    // ElMessage.info('执行数据接收查询');
    
    // 查询receive_log表获取真实数据
    const logResult = await db.query(`
      SELECT id, file_name, success_number, skip_number, update_number, fail_reason, created_at 
      FROM receive_log 
      ORDER BY created_at DESC
    `);
    
    // 使用Vue的响应式赋值方式
    const formattedData = logResult.map(item => ({
      id: item.id,
      fileName: item.file_name,
      successNumber: item.success_number,
      skipNumber: item.skip_number,
      updateNumber: item.update_number,
      failReason: item.fail_reason || '',
      operateTime: item.created_at
    }));
    
    // 先清空数组再添加新数据，确保响应式更新
    receiveTableData.value = []; // 清空数组
    receiveTableData.value = formattedData; // 重新赋值
    
    // 重置分页器
    receivePagination.value.currentPage = 1;
  } catch (error) {
    ElMessage.error('获取接收日志数据失败');
    console.error(error);
  }
};

const handleReleaseSizeChange = (newSize) => {
  releasePagination.value.pageSize = newSize;
  releasePagination.value.currentPage = 1;
};

const handleReleasePageChange = (newPage) => {
  releasePagination.value.currentPage = newPage;
};

const handleReceiveSizeChange = (newSize) => {
  receivePagination.value.pageSize = newSize;
  receivePagination.value.currentPage = 1;
};

const handleReceivePageChange = (newPage) => {
  receivePagination.value.currentPage = newPage;
};

const handleOperation = (row) => {
  ElMessage.info(`操作: ${row.fileName}`);
};

// 打开目录函数
const openDirectory = async (row) => {
  try {
    if (row.export_path) {
      // 使用预加载脚本中暴露的API
      await window.electronAPI.openDirectory(row.export_path);
    } else {
      ElMessage.warning('导出路径为空，无法打开目录');
    }
  } catch (error) {
    ElMessage.error('打开目录失败: ' + error.message);
    console.error('打开目录失败:', error);
  }
};

// 执行弹窗相关
const executeDialogVisible = ref(false);
const password = ref('');
const exportPath = ref('');
const executeLoading = ref(false); // 新增loading状态
const pathRules = ref([
  { required: true, message: '请选择导出路径', trigger: 'blur' }
]);
const passwordRules = ref([
  { required: true, message: '请输入密码', trigger: 'blur' }
]);

// 删除确认对话框
const deleteDialogVisible = ref(false);
const currentDeleteId = ref(null);

// 数据接收表格删除确认对话框
const receiveDeleteDialogVisible = ref(false);
const currentReceiveDeleteId = ref(null);

// 导入数据对话框
const importDialogVisible = ref(false);
const importPassword = ref('');
const importFilePath = ref('');
const conflictHandling = ref('skip'); // 'skip' 或 'update'
const importLoading = ref(false);

// 打开执行弹窗
const openExecuteDialog = () => {
  executeDialogVisible.value = true;
};

// 打开导入对话框
const openImportDialog = () => {
  importDialogVisible.value = true;
  importPassword.value = '';
  importFilePath.value = '';
  conflictHandling.value = 'skip';
};

// 选择导出路径
const selectExportPath = async () => {
  try {
    // 获取当前项目路径作为默认路径
    const projectPathResult = await window.electronAPI.invoke('get-project-path')
    
    // 检查获取项目路径是否成功
    if (!projectPathResult.success) {
      throw new Error('获取项目路径失败: ' + projectPathResult.error)
    }
    
    const projectPath = projectPathResult.path
    
    // 打开目录选择对话框
    const dialogResult = await window.electronAPI.invoke('show-open-dialog', {
      properties: ['openDirectory'],
      defaultPath: projectPath,
      title: '选择导出文件夹'
    })
    
    // 检查对话框操作是否成功
    if (!dialogResult.success) {
      throw new Error('打开目录选择对话框失败: ' + dialogResult.error)
    }
    
    // 如果用户选择了目录
    if (!dialogResult.canceled && dialogResult.filePaths && dialogResult.filePaths.length > 0) {
      exportPath.value = dialogResult.filePaths[0]
    }
  } catch (error) {
    ElMessage.error('选择目录失败，请重试')
    console.error('选择路径失败:', error)
  }
};

// 选择导入文件
const selectImportFile = async () => {
  try {
    // 获取当前项目路径作为默认路径
    const projectPathResult = await window.electronAPI.invoke('get-project-path')
    
    // 检查获取项目路径是否成功
    if (!projectPathResult.success) {
      throw new Error('获取项目路径失败: ' + projectPathResult.error)
    }
    
    const projectPath = projectPathResult.path
    
    // 打开文件选择对话框
    const dialogResult = await window.electronAPI.invoke('show-open-dialog', {
      properties: ['openFile'],
      defaultPath: projectPath,
      filters: [
        { name: '加密文件', extensions: ['enc'] }
      ],
      title: '选择数据发放导出的文件'
    })
    
    // 检查对话框操作是否成功
    if (!dialogResult.success) {
      throw new Error('打开文件选择对话框失败: ' + dialogResult.error)
    }
    
    // 如果用户选择了文件
    if (!dialogResult.canceled && dialogResult.filePaths && dialogResult.filePaths.length > 0) {
      importFilePath.value = dialogResult.filePaths[0]
    }
  } catch (error) {
    ElMessage.error('选择文件失败，请重试')
    console.error('选择文件失败:', error)
  }
};

// 取消导入
const cancelImport = () => {
  importDialogVisible.value = false;
  importPassword.value = '';
  importFilePath.value = '';
  conflictHandling.value = 'skip';
};

// 确认导入
const confirmImport = async () => {
  try {
    // 设置loading状态
    importLoading.value = true;
    
    // 检查密码
    if (!importPassword.value) {
      ElMessage.error('请输入密码');
      importLoading.value = false;
      return;
    }
    
    // 检查文件路径
    if (!importFilePath.value) {
      ElMessage.error('请选择文件');
      importLoading.value = false;
      return;
    }
    
    // 读取文件内容
    const readResult = await window.electronAPI.invoke('read-file', {
      filePath: importFilePath.value
    });
    
    if (!readResult.success) {
      throw new Error('读取文件失败: ' + readResult.error);
    }
    
    // 解密文件内容
    const decryptResult = await window.electronAPI.invoke('decrypt-file', {
      filePath: importFilePath.value,
      password: importPassword.value
    });
    
    if (!decryptResult.success) {
      throw new Error('解密失败: ' + decryptResult.error);
    }
    
    // 解析JSON数据
    let exportData;
    try {
      exportData = JSON.parse(decryptResult.content);
    } catch (parseError) {
      throw new Error('文件格式错误，无法解析JSON数据');
    }
    
    // 验证数据格式
    if (!exportData || !exportData.statements || !Array.isArray(exportData.statements)) {
      throw new Error('文件格式错误，缺少有效的SQL语句');
    }
    
    // 执行SQL语句
    ElMessage.info(`正在导入 ${exportData.statements.length} 条数据...`);
    
    let successCount = 0;
    let skipCount = 0;
    let updateCount = 0;
    
    for (const statement of exportData.statements) {
      try {
        // 检查是否是INSERT语句
        if (statement.trim().startsWith('INSERT INTO')) {
          // 提取表名
          const tableName = extractTableNameFromInsert(statement);
          
          if (tableName) {
            // 检查主键冲突
            const idValue = extractIdFromInsert(statement);
            
            if (idValue && await checkPrimaryKeyConflict(tableName, idValue)) {
              // 主键冲突，根据用户选择处理
              if (conflictHandling.value === 'update') {
                // 生成UPDATE语句
                const updateStatement = generateUpdateStatement(statement);
                await db.update(updateStatement);
                successCount++;
                updateCount++;
              } else {
                // 跳过
                skipCount++;
              }
            } else {
              // 没有冲突，直接执行INSERT语句
              // 如果语句中已经包含updated_at和updated_by字段，则直接执行
              if (statement.includes('updated_at') && statement.includes('updated_by')) {
                await db.insert(statement);
                successCount++;
              } else {
                // 如果语句中不包含updated_at和updated_by字段，则添加它们
                if (statement.trim().startsWith('INSERT INTO')) {
                  // 解析INSERT语句获取表名
                  const tableNameMatch = statement.match(/INSERT INTO\s+(\w+)/i);
                  if (tableNameMatch) {
                    // 添加updated_at和updated_by字段
                    const currentTime = new Date().toISOString().replace('T', ' ').replace('Z', '');
  // 使用本地时间而不是UTC时间
                    // const now = new Date();
                    // const currentTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;

                    const fileName = importFilePath.value ? importFilePath.value.split('\\').pop() : '未知文件';
                    const importInfo = `导入+${fileName}`;
                    
                    // 构建新的INSERT语句
                    // 1. 移除原INSERT语句末尾的分号（如果有）
                    const cleanStatement = statement.trim().endsWith(';') ? 
                      statement.trim().slice(0, -1) : statement.trim();
                      
                    // 2. 添加updated_at和updated_by字段到VALUES部分
                    const valuesMatch = cleanStatement.match(/VALUES\s*\(([^)]+)\)/i);
                    if (valuesMatch) {
                      const originalValues = valuesMatch[1];
                      const newValues = `${originalValues}, '${currentTime}', '${importInfo}'`;
                      const newInsertStatement = cleanStatement.replace(/VALUES\s*\([^)]+\)/i, `VALUES (${newValues})`);
                      await db.run(newInsertStatement);
                      successCount++;
                    } else {
                      // 如果无法解析VALUES部分，直接执行原语句
                      await db.run(statement);
                      successCount++;
                    }
                  } else {
                    // 无法解析表名，直接执行原语句
                    await db.query(statement);
                    successCount++;
                  }
                } else {
                  // 不是INSERT语句，直接执行
                  await db.query(statement);
                  successCount++;
                }
              }
            }
            }
          }
      } catch (error) {
        console.error('执行SQL语句失败:', error, 'SQL:', statement);
        // 继续执行下一条语句
      }
    }
    
    // 记录导入日志
    try {
      const fileName = importFilePath.value ? importFilePath.value.split('\\').pop() : '未知文件';
      const currentTime = new Date().toISOString().replace('T', ' ').replace('Z', '');
      
      await db.insert(
        `INSERT INTO receive_log (file_name, success_number, skip_number, update_number, fail_reason, created_at, updated_at, created_by, updated_by) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          fileName,
          successCount.toString(),
          skipCount.toString(),
          updateCount.toString(),
          '', // 成功时失败原因为空
          currentTime,
          currentTime,
          '1', // 假设当前用户ID为1
          '1'
        ]
      );
      console.log('导入日志记录成功');
    } catch (logError) {
      console.error('记录导入日志失败:', logError);
    }
    
    // 显示结果
    ElMessage.success(`导入完成！成功: ${successCount}, 跳过: ${skipCount}, 更新: ${updateCount}`);
    
    // 关闭对话框
    cancelImport();
    
    // 自动刷新接收数据表格
    await handleReceiveExecute();
    
    // 重置分页器
    receivePagination.value.currentPage = 1;
    
  } catch (error) {
    console.error('导入失败:', error);
    ElMessage.error('导入失败: ' + error.message);
    
    // 记录失败日志
    try {
      const fileName = importFilePath.value ? importFilePath.value.split('\\').pop() : '未知文件';
      const currentTime = new Date().toISOString().replace('T', ' ').replace('Z', '');
      
      await db.insert(
        `INSERT INTO receive_log (file_name, success_number, skip_number, update_number, fail_reason, created_at, updated_at, created_by, updated_by) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          fileName,
          '0',
          '0',
          '0',
          error.message, // 失败时记录失败原因
          currentTime,
          currentTime,
          '1', // 假设当前用户ID为1
          '1'
        ]
      );
      console.log('导入失败日志记录成功');
    } catch (logError) {
      console.error('记录导入失败日志失败:', logError);
    }
  } finally {
    importLoading.value = false;
  }
};

// 从插入语句中提取表名
const extractTableNameFromInsert = (sql) => {
  const match = sql.match(/INSERT INTO\s+(\w+)/i);
  return match ? match[1] : null;
};

// 从插入语句中提取ID值
const extractIdFromInsert = (sql) => {
  // 匹配 INSERT INTO table_name (id, field1, field2, ...) VALUES (value1, value2, ...)
  const match = sql.match(/INSERT INTO\s+\w+\s*\(\s*id[^)]*\)\s*VALUES\s*\(\s*([^,\s]+)/i);
  return match ? match[1].replace(/['"]/g, '') : null;
};

// 检查主键冲突
const checkPrimaryKeyConflict = async (tableName, idValue) => {
  try {
    const result = await db.query(
      `SELECT COUNT(*) as count FROM ${tableName} WHERE id = ?`,
      [idValue]
    );
    return result[0].count > 0;
  } catch (error) {
    console.error('检查主键冲突失败:', error);
    return false;
  }
};
// 生成UPDATE语句
const generateUpdateStatement = (insertStatement) => {
  // 解析INSERT语句
  const insertMatch = insertStatement.match(/INSERT INTO\s+(\w+)\s*\(([^)]+)\)\s*VALUES\s*\(([^)]+)\)/i);
  
  if (!insertMatch) {
    return null;
  }
  
  const tableName = insertMatch[1];
  const fields = insertMatch[2].split(',').map(f => f.trim());
  const values = insertMatch[3].split(',').map(v => v.trim());
  
  // 找到ID字段的位置
  const idIndex = fields.findIndex(f => f === 'id');
  
  if (idIndex === -1) {
    return null;
  }
  
  // 构建UPDATE语句
  const updateFields = fields.filter(f => f !== 'id');
  const updateValues = values.filter((v, i) => i !== idIndex);
  
  // 添加updated_at字段设置为当前时间
  // 添加updated_by字段设置为"导入+文件名"
  const currentTime = new Date().toISOString().replace('T', ' ').replace('Z', '');
  const fileName = importFilePath.value ? importFilePath.value.split('\\').pop() : '未知文件';
  const importInfo = `导入+${fileName}`;
  const setClause = updateFields.map((f, i) => `${f} = ${updateValues[i]}`).join(', ') + 
                   `, updated_at = '${currentTime}', updated_by = '${importInfo}'`;
  const whereClause = `id = ${values[idIndex]}`;
  
  return `UPDATE ${tableName} SET ${setClause} WHERE ${whereClause}`;
};

// 确认执行
const confirmExecute = async () => {
  try {
      console.log('开始执行数据导出...');
    // 设置loading状态
    executeLoading.value = true;
    
    // 检查是否选择了分组
    if (!releaseFilter.value.exportId) {
      ElMessage.error('请选择分组名');
      executeLoading.value = false;
      return;
    }
    
    // 检查时间范围是否完整
    if (releaseFilter.value.timeRange && releaseFilter.value.timeRange.length !== 2) {
      ElMessage.error('请选择完整的时间范围');
      executeLoading.value = false;
      return;
    }
    
    // 检查是否选择了导出路径
    if (!exportPath.value) {
      ElMessage.error('请选择导出路径');
      executeLoading.value = false;
      return;
    }
    
    // 检查是否输入了密码
    if (!password.value) {
      ElMessage.error('请输入密码');
      executeLoading.value = false;
      return;
    }
    
    // 根据分组名查询units、可查看的表及字段
    const result = await getExportConfigByGroupId(releaseFilter.value.exportId);
    
    if (!result || !result.units || !result.tables) {
      ElMessage.error('未找到有效的导出配置');
      executeLoading.value = false;
      return;
    }
    
    // 拼接SQL查询语句
    const sqlQueries = generateSQLQueries(result.units, result.tables, releaseFilter.value.timeRange);
    
    if (sqlQueries.length === 0) {
      ElMessage.error('未生成有效的SQL查询语句');
      executeLoading.value = false;
      return;
    }
    console.log('生成的SQL查询语句:', sqlQueries);
    
    // 执行SQL查询
    // ElMessage.info('正在执行SQL查询，请稍候...');
    const queryResults = await executeSQLQueries(sqlQueries);
    
    // 将查询结果转换为INSERT语句列表
    const insertStatements = convertToInsertStatements(queryResults);
    
    if (insertStatements.length === 0) {
      ElMessage.warning('没有查询到可导出的数据');
      executeLoading.value = false;
      return;
    }
    
    // 将INSERT语句转换为JSON格式以便更好地加密
    const exportData = {
      timestamp: new Date().toISOString(),
      count: insertStatements.length,
      statements: insertStatements
    };
    
    // 将数据转换为字符串
    const dataString = JSON.stringify(exportData, null, 2);
    
    // 生成文件名（带时间戳）
    const timestamp = new Date().getTime();
    const fileName = `export_${timestamp}.enc`;
    
    // 通过IPC调用主进程进行加密和写入文件
    const writeResult = await window.electronAPI.invoke('encrypt-and-write-file', {
      filePath: `${exportPath.value}/${fileName}`,
      content: dataString,
      password: password.value
    });
    
    if (!writeResult.success) {
      throw new Error(writeResult.error);
    }
    
    // 显示成功消息
    ElMessage.success(`成功导出 ${insertStatements.length} 条数据到文件: ${fileName}`);
    
    // 插入日志记录
    try {
      // 准备日志数据
      const timeRangeStr = releaseFilter.value.timeRange ? 
        `${releaseFilter.value.timeRange[0]}~${releaseFilter.value.timeRange[1]}` : '';
      
      // 直接执行数据库插入操作（使用insert()方法）
      await db.insert(
        `INSERT INTO delieve_log (group_name, time_range, file_name, export_path, created_by, updated_by) 
         VALUES (?, ?, ?, ?, ?, ?)`,
        [
          releaseFilter.value.exportId,
          timeRangeStr,
          fileName,
          exportPath.value,
          1, // 假设当前用户ID为1，实际应用中应从会话中获取
          1
        ]
      );
      
      console.log('日志记录插入成功');
    } catch (logError) {
      console.error('插入日志记录失败:', logError);
    }
    
    // 关闭弹窗
    executeDialogVisible.value = false;
    password.value = '';
    exportPath.value = '';
    
    // 自动刷新日志数据
    await getDelieveLogData();
    releasePagination.value.currentPage = 1;
  } catch (error) {
    console.error('执行失败:', error);
    ElMessage.error('执行失败: ' + error.message);
  } finally {
    // 无论成功还是失败，都要关闭loading状态
    executeLoading.value = false;
  }
};

// 将内容写入文件（示例函数，实际实现需要根据你的文件系统API调整）
const writeToFile = async (filePath, content) => {
  try {
    // 这里只是一个示例，实际实现需要根据你的文件系统API调整
    // 例如，使用Electron的fs模块或调用后端API
    console.log(`模拟写入文件: ${filePath}`);
    console.log('文件内容:', content);
    return true;
  } catch (error) {
    console.error('写入文件失败:', error);
    throw error;
  }
};

// 根据分组ID获取导出配置
const getExportConfigByGroupId = async (groupId) => {
  try {
    // 查询export表获取units信息
    const exportResult = await db.query(
      'SELECT * FROM export WHERE export_id = ?',
      [groupId]
    );
    
    if (!exportResult || exportResult.length === 0) {
      throw new Error('未找到对应的导出配置');
    }
    
    const exportData = exportResult[0];
    const units = exportData.units ? exportData.units.split(',') : [];
    
    // 查询export_subtable表获取可查看的表和字段信息
    const subtableResult = await db.query(
      'SELECT * FROM export_subtable WHERE export_id = ?',
      [groupId]
    );
    
    // 获取可查看的表信息（最多8张表）
    const tables = subtableResult.slice(0, 8).map(table => {
      const tableInfo = {
        name: table.table_name,
        columns: table.columns ? table.columns.split(',') : []
      };
      return tableInfo;
    });
    
    return {
      units: units,
      tables: tables
    };
  } catch (error) {
    console.error('获取导出配置失败:', error);
    throw error;
  }
};

// 生成SQL查询语句
const generateSQLQueries = (units, tables, timeRange) => {
  const queries = [];
  
  // 为每个表生成SQL查询
  tables.forEach(table => {
    // 检查表是否存在于我们的表名列表中
    if (!TABLE_NAMES.includes(table.name)) {
      return; // 跳过无效的表名
    }
    
    // 构建查询字段列表（包括系统字段和用户选择的字段）
    let fields = [...SYSTEM_FIELDS]; // 先添加系统字段
    if (table.columns && table.columns.length > 0) {
      fields = fields.concat(table.columns); // 再添加用户选择的字段
    }
    
    // 如果表有report_unit_code字段，需要添加单位过滤条件
    let whereConditions = [];
    if (fields.includes('report_unit_code')) {
      if (units && units.length > 0) {
        const unitList = units.map(unit => `'${unit}'`).join(',');
        whereConditions.push(`report_unit_code IN (${unitList})`);
      }
    }
    
    // 添加时间范围条件
    if (timeRange && timeRange.length === 2) {
      const startDate = timeRange[0];
      const endDate = timeRange[1];
      
      // 调试日志：输出原始日期值
      console.log('原始日期值 - startDate:', startDate, 'endDate:', endDate);
      
      // 由于日期格式为 yyyy-11-Sa 这种非标准格式，需要特殊处理
      // 提取年份、月份和星期几
        const parseDate = (dateStr) => {
          // 首先检查是否是标准日期格式 yyyy-MM-dd
          const standardMatch = dateStr.match(/^(\d{4})-(\d{2})-(\d{2})$/);
          if (standardMatch) {
            const year = standardMatch[1];
            const month = standardMatch[2];
            const day = standardMatch[3];
            
            console.log(`解析成功（标准格式）: ${dateStr} -> ${year}-${month}-${day}`);
            return { 
              firstDay: `${year}-${month}-${day}`, 
              lastDay: `${year}-${month}-${day}` 
            };
          }
          
          // 匹配 yyyy-yy-ww 格式的日期（其中ww是星期几的缩写）
          const match = dateStr.match(/^(\d{4})-(\d{2})-(\w{2})$/);
          if (match) {
            const year = match[1];
            const month = match[2];
            const weekday = match[3]; // 星期几的缩写（如Sa, Su等）
            
            // 计算该月的第一天是星期几
            const firstDayOfMonth = new Date(year, parseInt(month) - 1, 1);
            const firstDayWeekday = firstDayOfMonth.toLocaleDateString('en-US', { weekday: 'short' }).substring(0, 2);
            
            // 计算目标日期是该月的第几天
            const weekdaysOrder = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
            const targetWeekdayIndex = weekdaysOrder.indexOf(weekday);
            const firstDayIndex = weekdaysOrder.indexOf(firstDayWeekday);
            
            let dayOfMonth = 1;
            if (targetWeekdayIndex >= firstDayIndex) {
              dayOfMonth = targetWeekdayIndex - firstDayIndex + 1;
            } else {
              dayOfMonth = 7 - (firstDayIndex - targetWeekdayIndex) + 1;
            }
            
            // 确保日期有效
            const maxDaysInMonth = new Date(year, parseInt(month), 0).getDate();
            if (dayOfMonth > maxDaysInMonth) {
              dayOfMonth = maxDaysInMonth;
            }
            
            const formattedDay = String(dayOfMonth).padStart(2, '0');
            const targetDate = `${year}-${month}-${formattedDay}`;
            
            console.log(`解析成功（非标准格式）: ${dateStr} -> ${targetDate}`);
            
            return { 
              firstDay: targetDate, 
              lastDay: targetDate 
            };
          }
          
          // 尝试从字符串中提取年份、月份和日期
          const yearMatch = dateStr.match(/(\d{4})/);
          const monthMatch = dateStr.match(/(\d{2})/);
          const dayMatch = dateStr.match(/(\d{2})/);
          
          if (yearMatch && monthMatch) {
            const year = yearMatch[1];
            const month = monthMatch[1];
            const day = dayMatch ? dayMatch[1] : '01';
            
            const targetDate = `${year}-${month}-${day}`;
            console.log(`解析成功（部分匹配）: ${dateStr} -> ${targetDate}`);
            
            return { 
              firstDay: targetDate, 
              lastDay: targetDate 
            };
          }
          
          // 如果所有解析方法都失败，使用当前日期
          const currentDate = new Date();
          const year = currentDate.getFullYear().toString();
          const month = String(currentDate.getMonth() + 1).padStart(2, '0');
          const day = String(currentDate.getDate()).padStart(2, '0');
          const fallbackDate = `${year}-${month}-${day}`;
          
          console.log(`解析失败，使用当前日期: ${dateStr} -> ${fallbackDate}`);
          
          return { 
            firstDay: fallbackDate, 
            lastDay: fallbackDate 
          };
        };
      
      try {
        const startDateInfo = parseDate(startDate);
        const endDateInfo = parseDate(endDate);
        
        // 构建完整的时间范围条件
        const startDateTime = `${startDateInfo.firstDay} 00:00:00`;
        const endDateTime = `${endDateInfo.lastDay} 23:59:59`;
        
        // 调试日志：输出最终的时间范围条件
        console.log('最终时间范围条件:', `created_at BETWEEN '${startDateTime}' AND '${endDateTime}'`);
        
        whereConditions.push(`created_at BETWEEN '${startDateTime}' AND '${endDateTime}'`);
      } catch (error) {
        console.error('日期解析错误:', error);
        throw new Error(`日期格式错误: ${error.message}`);
      }
    } else {
      // 调试日志：当时间范围无效时输出信息
      console.log('时间范围无效或不完整:', timeRange);
    }
    
    // 构建完整SQL查询
    const selectFields = fields.join(', ');
    let sql = `SELECT ${selectFields} FROM ${table.name}`;
    
    if (whereConditions.length > 0) {
      sql += ` WHERE ${whereConditions.join(' AND ')}`;
    }
    
    queries.push(sql);
  });
  
  return queries;
};

// 执行SQL查询
const executeSQLQueries = async (sqlQueries) => {
  try {
    const results = [];
    
    for (const sql of sqlQueries) {
      // 执行SQL查询
      const queryResult = await db.query(sql);
      
      // 记录查询结果
      results.push({
        sql: sql,
        tableName: extractTableNameFromSQL(sql),
        data: queryResult
      });
    }
    
    return results;
  } catch (error) {
    console.error('执行SQL查询失败:', error);
    throw error;
  }
};

// 从SQL语句中提取表名
const extractTableNameFromSQL = (sql) => {
  // 简单的正则表达式匹配表名（适用于简单的SELECT语句）
  const match = sql.match(/FROM\s+(\w+)/i);
  return match ? match[1] : null;
};

// 将查询结果转换为INSERT语句列表
const convertToInsertStatements = (queryResults) => {
  const insertStatements = [];
  
  queryResults.forEach(result => {
    const tableName = result.tableName;
    const data = result.data;
    
    if (!tableName || !data || data.length === 0) {
      return;
    }
    
    // 获取字段名（从第一条记录）
    const fields = Object.keys(data[0]);
    
    // 为每条记录生成INSERT语句
    data.forEach(row => {
      // 准备字段值
      const values = fields.map(field => {
        const value = row[field];
        
        // 根据数据类型处理值
        if (value === null || value === undefined) {
          return 'NULL';
        } else if (typeof value === 'string') {
          // 转义单引号
          const escapedValue = value.replace(/'/g, "''");
          return `'${escapedValue}'`;
        } else if (typeof value === 'number') {
          return value;
        } else if (value instanceof Date) {
          return `'${value.toISOString()}'`;
        } else {
          // 其他类型，转换为字符串
          return `'${String(value)}'`;
        }
      });
      
      // 生成INSERT语句
      const insertStatement = `INSERT INTO ${tableName} (${fields.join(', ')}) VALUES (${values.join(', ')});`;
      insertStatements.push(insertStatement);
    });
  });
  
  return insertStatements;
};

// 日期变化处理函数
const handleDateChange = (val) => {
  if (val && val.length === 2) {
    // 确保日期格式正确
    const formatDate = (date) => {
      if (typeof date === 'string') {
        // 如果已经是字符串格式，直接返回
        return date;
      } else if (date instanceof Date) {
        // 如果是Date对象，格式化为YYYY-MM-DD
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      } else {
        // 其他类型，尝试转换为字符串
        return String(date);
      }
    };
    
    const formattedStartDate = formatDate(val[0]);
    const formattedEndDate = formatDate(val[1]);
    
    // 更新releaseFilter.timeRange的值
    releaseFilter.value.timeRange = [formattedStartDate, formattedEndDate];
    
    console.log('日期变化处理 - 格式化后的日期:', formattedStartDate, formattedEndDate);
  }
};

// 取消执行
const cancelExecute = () => {
  executeDialogVisible.value = false;
  password.value = '';
  exportPath.value = '';
};

// 打开删除确认对话框（数据发放表格）
const openDeleteDialog = (row) => {
  currentDeleteId.value = row.id;
  deleteDialogVisible.value = true;
};

// 确认删除（数据发放表格）
const confirmDelete = async () => {
  try {
    if (!currentDeleteId.value) {
      ElMessage.error('请选择要删除的数据');
      return;
    }
    
    // 执行删除操作
    await db.delete('DELETE FROM delieve_log WHERE id = ?', [currentDeleteId.value]);
    
    // 显示成功消息
    ElMessage.success('删除成功');
    
    // 关闭对话框
    deleteDialogVisible.value = false;
    currentDeleteId.value = null;
    
    // 刷新表格数据
    await getDelieveLogData();
    releasePagination.value.currentPage = 1;
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败: ' + error.message);
  }
};

// 取消删除（数据发放表格）
const cancelDelete = () => {
  deleteDialogVisible.value = false;
  currentDeleteId.value = null;
};

// 打开删除确认对话框（数据接收表格）
const openReceiveDeleteDialog = (row) => {
  currentReceiveDeleteId.value = row.id;
  receiveDeleteDialogVisible.value = true;
};

// 确认删除（数据接收表格）
const confirmReceiveDelete = async () => {
  try {
    if (!currentReceiveDeleteId.value) {
      ElMessage.error('请选择要删除的数据');
      return;
    }
    
    // 执行删除操作
    await db.delete('DELETE FROM receive_log WHERE id = ?', [currentReceiveDeleteId.value]);
    
    // 显示成功消息
    ElMessage.success('删除成功');
    
    // 关闭对话框
    receiveDeleteDialogVisible.value = false;
    currentReceiveDeleteId.value = null;
    
    // 刷新表格数据
    await handleReceiveExecute();
    receivePagination.value.currentPage = 1;
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败: ' + error.message);
  }
};

// 取消删除（数据接收表格）
const cancelReceiveDelete = () => {
  receiveDeleteDialogVisible.value = false;
  currentReceiveDeleteId.value = null;
};
</script>

<template>
  <!-- 执行弹窗 -->
  <el-dialog
    v-model="executeDialogVisible"
    title="执行操作"
    :width="'60%'"
    :before-close="cancelExecute"
  >
    <el-form label-position="top">
      <el-form-item label="密码" required>
        <el-input
          v-model="password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
              <el-form-item label="导出路径" required>
                <div class="path-input-group">
                  <el-input
                    v-model="exportPath"
                    placeholder="请选择导出路径"
                    readonly
                    :rules="pathRules"
                  />
                  <el-button
                    type="primary"
                    @click="selectExportPath"
                  >
                    选择路径
                  </el-button>
                </div>
              </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelExecute">取消</el-button>
        <el-button type="primary" @click="confirmExecute">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 删除确认弹窗（数据发放表格） -->
  <el-dialog
    v-model="deleteDialogVisible"
    title="确认删除"
    width="30%"
    :before-close="cancelDelete"
  >
    <span>您确定要删除这条记录吗？</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDelete">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 删除确认弹窗（数据接收表格） -->
  <el-dialog
    v-model="receiveDeleteDialogVisible"
    title="确认删除"
    width="30%"
    :before-close="cancelReceiveDelete"
  >
    <span>您确定要删除这条记录吗？</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelReceiveDelete">取消</el-button>
        <el-button type="danger" @click="confirmReceiveDelete">确认删除</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 导入数据弹窗 -->
  <el-dialog
    v-model="importDialogVisible"
    title="导入数据"
    width="50%"
    :before-close="cancelImport"
  >
    <el-form label-position="top">
      <el-form-item label="密码" required>
        <el-input
          v-model="importPassword"
          type="password"
          placeholder="请输入解密密码"
          show-password
        />
      </el-form-item>
      
      <el-form-item label="选择文件" required>
        <div class="file-selector-group">
          <el-input
            v-model="importFilePath"
            placeholder="请选择数据发放导出的文件"
            readonly
            class="file-selector-input"
          />
          <el-button type="primary" @click="selectImportFile" class="file-selector-button">
            选择文件
          </el-button>
        </div>
      </el-form-item>
      
      <el-form-item label="冲突处理" required>
        <el-radio-group v-model="conflictHandling">
          <el-radio label="skip">遇到冲突不覆盖</el-radio>
          <el-radio label="update">遇到冲突覆盖原数据</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelImport">取消</el-button>
        <el-button type="primary" :loading="importLoading" @click="confirmImport">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>

  <div class="page-container">
    <!-- 顶部导航栏 -->
    <TopNav />

    <!-- 内容区域用 Card 包裹 -->
    <div class="content-wrapper">
      <el-card class="box-card">
        <!-- 数据发放 Tab -->
        <div v-if="activeTab === 'release'" class="tab-content">
          <div class="sub-tabs">
            <div class="sub-tab" :class="{ active: subTab === 'release' }" @click="subTab = 'release'; activeTab = 'release'">
              数据发放
            </div>
            <div class="sub-tab" :class="{ active: subTab === 'receive' }" @click="subTab = 'receive'; activeTab = 'receive'">
              数据接收
            </div>
          </div>

          <!-- 发放内容 -->
          <div class="tab-body">
            <div class="filter-bar-container">
              <div class="filter-item">
                <span class="filter-label">分组名</span>
                <el-select
                  v-model="releaseFilter.exportId"
                  placeholder="请选择"
                  clearable
                  class="filter-select"
                  filterable                >
                  <el-option 
                    v-for="group in exportGroups" 
                    :key="group.value" 
                    :label="group.label" 
                    :value="group.value"
                  ></el-option>
                </el-select>
              </div>
              
              <div class="filter-item time-range-item">
                <span class="filter-label">时间范围</span>
              <el-date-picker
                v-model="releaseFilter.timeRange"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                class="date-range-picker"
                :unlink-panels="true"
                @change="handleDateChange"
                :default-value="[new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), new Date()]"
              />
              </div>
              
              <div class="filter-item execute-btn-item">
                <el-button type="primary" class="execute-btn" @click="openExecuteDialog" >
                  执行导出
                </el-button>
              </div>
            </div>

            <!-- 数据表格 -->
            <div class="table-wrapper">
              <el-table :data="paginatedReleaseData" stripe style="width: 100%">
                <!-- <el-table-column prop="id" label="序号" width="60" align="center"></el-table-column> -->
                     <el-table-column type="index" width="50" />
                <el-table-column prop="group_name" label="分组名" min-width="60"  align="center"></el-table-column>
                <el-table-column prop="time_range" label="时间范围"  align="center"></el-table-column>
                <el-table-column prop="file_name" label="文件名称"  align="center"></el-table-column>
                <el-table-column prop="export_path" label="导出路径" min-width="200" align="center"></el-table-column>
                <el-table-column prop="created_at" label="操作时间" width="200" align="center"></el-table-column>
                <el-table-column label="操作" width="200" fixed="right" align="center">
                  <template #default="{ row }">
                    <el-button size="mini"  type="primary" @click="openDirectory(row)">打开目录</el-button>
                    <el-button size="mini"  type="danger" @click="openDeleteDialog(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 分页器 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="releasePagination.currentPage"
                v-model:page-size="releasePagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="releaseTableData.length"
                layout="total, sizes, prev, pager, next, jumper"
                :pager-count="5"
                @size-change="handleReleaseSizeChange"
                @current-change="handleReleasePageChange"
              />
            </div>
          </div>
        </div>

        <!-- 数据接收 Tab -->
        <div v-if="activeTab === 'receive'" class="tab-content">
          <div class="sub-tabs">
            <div class="sub-tab" :class="{ active: subTab === 'release' }" @click="subTab = 'release'; activeTab = 'release'">
              数据发放
            </div>
            <div class="sub-tab" :class="{ active: subTab === 'receive' }" @click="subTab = 'receive'; activeTab = 'receive'">
              数据接收
            </div>
          </div>

          <div class="tab-body">
            <div class="filter-bar" style="justify-content: flex-start;">
              <el-button type="primary" size="large" @click="openImportDialog">
                <el-icon><Upload /></el-icon>
                <span>导入</span>
              </el-button>
            </div>
            <div class="table-wrapper">
            <el-table :data="paginatedReceiveData" stripe style="width: 100%">
              <!-- <el-table-column prop="id" label="序号" width="60"></el-table-column> -->
               <el-table-column type="index" width="50" />
              <el-table-column prop="fileName" label="文件名称"  align="center"></el-table-column>
              <el-table-column prop="successNumber" label="成功数量"  align="center"></el-table-column>
              <el-table-column prop="skipNumber" label="跳过数量"  align="center"></el-table-column>
              <el-table-column prop="updateNumber" label="更新数量"  align="center"></el-table-column>
              <el-table-column prop="failReason" label="失败原因"  align="center"></el-table-column>
              <el-table-column prop="operateTime" label="操作时间" min-width="120" align="center"></el-table-column>
              <!-- <el-table-column prop="operateTime" label="操作时间" width="150"></el-table-column> -->
              <el-table-column label="操作" width="90" fixed="right" align="center">
                <template #default="{ row }">
                  <el-button  size="mini"  type="danger" @click="openReceiveDeleteDialog(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            </div>
            <!-- 分页器 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="receivePagination.currentPage"
                v-model:page-size="receivePagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="receiveTableData.length"
                layout="total, sizes, prev, pager, next, jumper"
                :pager-count="5"
                @size-change="handleReceiveSizeChange"
                @current-change="handleReceivePageChange"
              />
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
/* 执行弹窗样式 - 与settings.vue保持一致 */
.path-input-group {
  display: flex;
  gap: 12px;
  width: 100%;
  align-items: center;
}

.path-input-group .el-input {
  flex: 1;
  min-width: 0;
}

.path-input-group .el-button {
  flex-shrink: 0;
  width: 120px;
  height: 44px;
  font-size: 15px;
  font-weight: 500;
}

/* 文件选择组样式 */
.file-selector-group {
  display: flex;
  gap: 12px;
  width: 100%;
  align-items: center;
}

.file-selector-input {
  flex: 1;
  min-width: 0;
}

.file-selector-button {
  flex-shrink: 0;
  height: 40px;
  font-size: 15px;
  font-weight: 500;
}

/* 确保所有输入框高度一致 */
:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
}

/* 调整标签样式 */
:deep(.el-form-item__label) {
  line-height: 1.5;
  padding-bottom: 8px;
}

/* 文件选择组样式 */
.file-selector-group {
  display: flex;
  gap: 12px;
  width: 100%;
  align-items: center;
}

.file-selector-input {
  flex: 1;
  min-width: 0;
}

.file-selector-button {
  flex-shrink: 0;
  height: 40px;
  font-size: 15px;
  font-weight: 500;
}

/* 确保所有输入框高度一致 */
:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
}

/* 调整标签样式 */
:deep(.el-form-item__label) {
  line-height: 1.5;
  padding-bottom: 8px;
}

/* 调整弹窗宽度 */
:deep(.el-dialog) {
  width: 60%;
  min-width: 700px;
}

/* 统一输入框样式 */
:deep(.el-form-item) {
  margin-bottom: 22px;
  width: 100%;
}

:deep(.el-form-item__content) {
  width: 100%;
}

/* 密码输入框样式 */
:deep(.password-input .el-input) {
  width: 100%;
}

/* 路径选择器样式 */
:deep(.path-selector .el-input) {
  flex: 1;
}

/* 确保所有输入框高度一致 */
:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
  font-size: 16px; /* 增加字体大小 */
}

/* 表单标签样式 */
:deep(.el-form-item__label) {
  font-size: 14px; /* 增加标签字体大小 */
  font-weight: bold;
}

/* 按钮样式 */
:deep(.path-selector .el-button) {
  margin-left: 10px;
  height: 40px;
}

.page-container {
  display: flex;
  flex-direction: column;
  height: 98vh;
  background: #f5f6f8;
}

.content-wrapper {
  flex: 1;
  padding: 10px;
  overflow: hidden;
}

.box-card {
  height: 100%;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  padding: 20px;
  flex: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

.tab-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.sub-tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 2px solid #e0e0e0;
  flex-shrink: 0;
}

.sub-tab {
  padding: 12px 20px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  color: #666;
  border-bottom: 3px solid transparent;
  transition: all 0.3s;
}

.sub-tab.active {
  color: #0052cc;
  border-bottom-color: #0052cc;
}

.tab-body {
  flex: 1;
  overflow: auto;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: auto;
  margin-top: 20px;
}

/* 自定义滚动条样式 */
.table-wrapper::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.table-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.table-wrapper::-webkit-scrollbar-thumb {
  background: #bfbfbf;
  border-radius: 10px;
  transition: background 0.3s ease;
}

.table-wrapper::-webkit-scrollbar-thumb:hover {
  background: #888;
}
.filter-bar{
  display: flex;
  justify-content: flex-end;
}

.filter-bar-container {
  display: flex;
  align-items: center;
  gap: 10px;

  flex-wrap: wrap;
}
.filter-item {
  display: flex;
  align-items: center;
  min-width: 180px;
}

.filter-label {
  font-weight: 500;
  color: #333;
  margin-right: 8px;
  white-space: nowrap;
  font-size: 16px;
}

.filter-select {
  width: 100%;
}

.date-range-picker {
  width: 140px;
}

/* 为下属单位选择框设置更宽的宽度 */
.filter-item:first-child .filter-select {
  width: 220px;
}

.execute-btn {
  min-width: 80px;
}

/* 更紧凑的日期选择器内部样式 */
:deep(.el-date-range-picker .el-input__wrapper) {
  padding: 0 4px;
}

:deep(.el-date-range-picker .el-range-separator) {
  padding: 0 2px;
}

:deep(.el-date-range-picker) {
  width: 140px !important;
}

.pagination-container {
  display: flex;
  justify-content: center;  /* 改为居中显示 */
  align-items: center;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
  flex-shrink: 0;
}

/* 确保分页器中文显示 */
:deep(.el-pagination) {
  --el-pagination-font-size: 14px;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next),
:deep(.el-pagination .more) {
  font-family: var(--el-font-family);
}

:deep(.el-pagination__jump) {
  font-family: var(--el-font-family);
}

:deep(.el-pagination__editor) {
  font-family: var(--el-font-family);
}

:deep(.el-pagination__total) {
  font-family: var(--el-font-family);
}

:deep(.el-pagination__sizes) {
  font-family: var(--el-font-family);
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}
</style>